package batch

import (
	"cid-media-api/config"
	"cid-media-api/global"
	"cid-media-api/internal/adcore"
	"cid-media-api/internal/factory"
	Models "cid-media-api/models"
	BatchModel "cid-media-api/models/batch"
	"context"
	"fmt"
	"github.com/streadway/amqp"
	"log"
	"time"
)

// 添加RabbitMQ连接结构体
type RabbitMQConn struct {
	conn    *amqp.Connection
	channel *amqp.Channel
}

func Batch() {
	//rabbitMQ := initRabbitMQ()
	//defer rabbitMQ.Close()

	//msgs := consumeMessages(rabbitMQ.channel)
	//forever := make(chan bool)

	//go processMessages(msgs)

	//log.Printf(" [*] Waiting for batch messages. To exit press CTRL+C")
	//<-forever

	handleMessage()
}

// 初始化RabbitMQ连接
func initRabbitMQ() *RabbitMQConn {
	cfg := config.AppConfig.RabbitMQ

	conn, err := amqp.Dial(cfg.URL)
	if err != nil {
		log.Fatalf("Failed to connect to RabbitMQ: %v", err)
	}

	channel, err := conn.Channel()
	if err != nil {
		log.Fatalf("Failed to open a channel: %v", err)
	}

	_, err = channel.QueueDeclare(
		cfg.BatchQueue, // 队列名称
		true,           // 持久化
		false,          // 自动删除
		false,          // 排他性
		false,          // 等待
		nil,            // 参数
	)
	if err != nil {
		log.Fatalf("Failed to declare a queue: %v", err)
	}

	return &RabbitMQConn{
		conn:    conn,
		channel: channel,
	}
}

// 消费消息
func consumeMessages(channel *amqp.Channel) <-chan amqp.Delivery {
	cfg := config.AppConfig.RabbitMQ

	msgs, err := channel.Consume(
		cfg.BatchQueue, // 队列名称
		"",             // 消费者标签
		false,          // 自动应答（改为手动确认）
		false,          // 排他性
		false,          // 本地
		false,          // 等待
		nil,            // 参数
	)
	if err != nil {
		log.Fatalf("Failed to register a consumer: %v", err)
	}

	return msgs
}

// 消息处理
func processMessages(msgs <-chan amqp.Delivery) {
	for msg := range msgs {
		log.Printf("Received a message: %s", msg.Body)

		// 在这里添加你的业务处理逻辑
		//if handleMessage(msg.Body) {
		//	msg.Ack(false) // 处理成功，手动确认
		//} else {
		//	msg.Nack(false, true) // 处理失败，重新入队
		//}
	}
}

// 关闭连接
func (r *RabbitMQConn) Close() {
	r.channel.Close()
	r.conn.Close()
}

// 示例消息处理函数
func handleMessage() bool {
	log.Println(" 批量创建任务开始.......")
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	var BatchAdCreationTasks []BatchModel.BatchAdCreationTask

	BatchAdCreationTaskQuery := global.CidDb.Model(&BatchModel.BatchAdCreationTask{}).
		Where("status not in (?)", "0,6")

	// 执行查询，并将结果存入mediaAccounts中，如果出错则打印错误并返回
	err := BatchAdCreationTaskQuery.Find(&BatchAdCreationTasks).Error
	if err != nil {
		fmt.Println("获取批量创建任务列表失败:", err)
		return false
	}

	// 遍历批量创建任务列表，逐个执行创建操作
	for _, task := range BatchAdCreationTasks {
		// 解析 task.AdvertiserIDs 并遍历，获取对应的媒体账户信息
		for _, advertiserID := range task.AdvertiserIDs {
			// 查询媒体账户信息
			var mediaAccount Models.MediaAccount
			mediaErr := global.CidDb.Model(&Models.MediaAccount{}).Where("id =?", advertiserID).First(&mediaAccount).Error
			if mediaErr != nil {
				fmt.Println("获取媒体账户信息失败:", mediaErr)
				return false
			}

			// 查询批量创建任务列表, 获取对应的创建器
			advertiserID := mediaAccount.AdvertiserId // 媒体账户ID
			accessToken := mediaAccount.AccessToken   // 媒体账户ID
			creator := factory.GetBatchCreator(advertiserID, accessToken, mediaAccount.MediaId)

			prjTmplId := task.ProjectTemplateID
			var BatchProjectTemplateData BatchModel.BatchProjectTemplate
			prjErr := global.CidDb.Model(&BatchModel.BatchProjectTemplate{}).Where("id =?", prjTmplId).First(&BatchProjectTemplateData).Error
			if prjErr != nil {
				fmt.Println("获取项目模板失败:", prjErr)
				return false
			}

			// 获取广告模板id
			var BatchPromotionTemplateData BatchModel.BatchPromotionTemplate
			promoTmplId := task.ProjectTemplateID
			promoErr := global.CidDb.Model(&BatchModel.BatchPromotionTemplate{}).Where("id =?", promoTmplId).First(&BatchPromotionTemplateData).Error
			if promoErr != nil {
				fmt.Println("获取广告模板失败:", promoErr)
				return false
			}

			// 构造请求
			req := adcore.BatchRequest{
				AdGroup: adcore.AdGroupParams{
					Template: BatchProjectTemplateData,
				},
				Ad: adcore.AdParams{
					Template: BatchPromotionTemplateData,
				},
			}
			// 执行批量创建
			result, err := creator.BatchCreate(ctx, req)
			if err != nil {
				fmt.Println("Error:", err)
				// 记录失败任务 TODO
			}
			fmt.Printf("Result:\nCampaignIDs: %v\nAdGroupIDs: %v\nAdIDs: %v\n",
				result.CampaignIDs, result.AdGroupIDs, result.AdIDs)
		}
	}

	return true
}
